package com.jsits.v2x.common.connection.socket;

import java.nio.ByteBuffer;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

public class MessageEncoder implements ProtocolEncoder 
{
	/*
	 * 缓冲区消息最长长度	
	 */
	private static final int MAX_MESSAGE_LEN = 10240;
	
    /*
     * 客户端发送消息至服务端的编码入口函数
     * @see org.apache.mina.filter.codec.ProtocolEncoder#encode(org.apache.mina.core.session.IoSession, java.lang.Object, org.apache.mina.filter.codec.ProtocolEncoderOutput)
     */
	public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception 
	{
		ByteBuffer byteBuffer = ByteBuffer.allocate(MAX_MESSAGE_LEN);
		
		//对发送的消息进行编码，如果编码成功则将消息发送至服务端
		SocketMessage socketMessage = (SocketMessage)message;
		if (socketMessage.generateMessage(byteBuffer)) 
		{
			IoBuffer tmpBuf = IoBuffer.allocate(byteBuffer.limit());
			tmpBuf.put(byteBuffer);
			tmpBuf.flip();
	        out.write(tmpBuf);
	        tmpBuf.free();
	        tmpBuf = null;
		}
    }

    public void dispose(IoSession session) throws Exception 
    {
    }
}
